// src/main/java/org/example/backend/repository/InternshipRepository.java
package org.example.backend.repository;

import org.example.backend.dto.StudentInternshipInfoDto;
import org.example.backend.entity.Internship;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface InternshipRepository extends JpaRepository<Internship, Long> {
    Optional<Internship> findByStudentIdAndApplicationId(Long studentId, Long applicationId);

//    List<Internship> findByStudentId(Long studentId);
//
//    List<Internship> findByTeacherId(Long teacherId);
//
//    List<Internship> findByCompanyId(Long companyId);
    Optional<Internship> findByStudentId(Long studentId);
    @Query("SELECT CASE WHEN COUNT(i) > 0 THEN true ELSE false END FROM Internship i WHERE i.id = :internshipId AND i.companyId = :companyId")
    boolean existsByIdAndCompanyId(@Param("internshipId") Long internshipId, @Param("companyId") Long companyId);
    @Query("SELECT i FROM Internship i WHERE i.studentId IN :studentIds")
    List<Internship> findByStudentIds(@Param("studentIds") List<Long> studentIds);
    Page<Internship> findByStudentId(Long studentId, Pageable pageable);
    Page<Internship> findByTeacherId(Long teacherId, Pageable pageable);
    Page<Internship> findByCompanyId(Long companyId, Pageable pageable);
    Optional<Internship> findByApplicationId(Long applicationId);

    long countByStatus(Integer status);

    @Query("SELECT COUNT(DISTINCT i.studentId) FROM Internship i")
    long countDistinctStudents();

    // 在 InternshipRepository.java 中修改查询方法
    @Query("SELECT new org.example.backend.dto.StudentInternshipInfoDto(i.studentId, i.id, ip.title, c.name) " +
            "FROM Internship i " +
            "JOIN InternshipPosition ip ON i.positionId = ip.id " +
            "JOIN Company c ON ip.companyId = c.id " +
            "WHERE i.studentId = :studentId")
    List<StudentInternshipInfoDto> findInternshipInfoByStudentId(@Param("studentId") Long studentId);

    @Query("SELECT i FROM Internship i WHERE i.teacherId = :teacherId AND i.id NOT IN " +
            "(SELECT e.internshipId FROM Evaluation e WHERE e.evaluatorType = 1 AND e.evaluatorId = :teacherId)")
    Page<Internship> findPendingEvaluationsByTeacher(@Param("teacherId") Long teacherId, Pageable pageable);

}
